#! /usr/bin/env python3
# -*- coding: utf-8 -*-

from utils import *
from search import *
import tsp, argparse, textwrap, time

def randomized_max_value(problem, limit=100):
    current = LSNode(problem, problem.initial, 0)
    for step in range(limit):
        bests = PriorityQueue(LSNode.value)
        for node in current.expand():
            if len(bests) > 5:
                curr = bests.pop()
                if node.value() > curr.value():
                    curr = node
                bests.append(curr)
            else:
                bests.append(node)
        current = random.choice([bests.pop() for X in range(5)])
    return current

if __name__ == "__main__":
    parser = argparse.ArgumentParser(formatter_class = argparse.RawDescriptionHelpFormatter,
            description = textwrap.dedent('''\
                    Assignement 4 : LINGI2261 - Traveling Salesman Problem
                    ------------------------------------------------------
                    '''),
            epilog = "----------------------------------------------------\n---- author : group30 - Crecun Eduard, Gerard Nicolas")
    parser.add_argument("f", action = "store", help = "The file where distances between cities are stored")
    
    args = parser.parse_args()
    
    problem = tsp.TSPProblem(args.f)
    
    start = time.time()

    node = randomized_max_value(problem)
    
    stop = time.time()

    fd = open("results/results_randomized_maxvalue.txt", "a", encoding='utf-8')
    fd.write("---Test over ")
    fd.write(args.f)
    fd.write("\n")
    fd.write("\nBest path : ")
    fd.write(repr(node.state.pathway))
    fd.write("\n\nCost is : ")
    fd.write(repr(node._value * -1))
    fd.write("\nTime lapsed : ")
    fd.write(repr(stop - start))
    fd.write("\nBest step : ")
    fd.write(repr(node.step))
    fd.write("\n\n\n\n")
    fd.close()

    print("\nBest path is : ", node.state.pathway)
    print("\nCost is : ", node._value * -1, "\t(the lower the better)")
    print("Time lapsed : ", (stop - start))
    print("\n")
